<template>
  <div class="app-container">
    <el-card>
      <div v-if="showSearch" slot="header" class="clearfix">
        <!--头部工具过滤-->
        <el-input v-model="listQuery.name" size="mini" maxlength="255" clearable style="width: 200px;margin-right: 5px;" placeholder="请输入菜单名称" />
        <el-button type="success" size="mini" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button type="warning" size="mini" icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
      </div>
      <div class="opts">
        <!--左侧-->
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate">添加</el-button>
        <el-button type="success" :disabled="hasEdiObj" icon="el-icon-edit" size="mini" @click="handleUpdate(selectionChange[0])">修改</el-button>
        <el-button type="danger" :disabled="hasDelObj" icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
        <!--右侧-->
        <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="resetForm" />
      </div>
      <!--表格数据-->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;"
        row-key="id"
        size="mini"
        element-loading-text="正在努力加载中..."
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        highlight-current-row
        border
        fit
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns[0].visible" prop="name" label="部门名称" />
        <el-table-column v-if="columns[1].visible" prop="sort" label="排序" />
        <el-table-column v-if="columns[2].visible" prop="enabled" label="是否启用">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enabled" active-color="#13ce66" inactive-color="#ff4949" @change="updateEnabled({id: scope.row.id,enabled: scope.row.enabled},scope.row)" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" prop="createdBy" label="创建人">
          <template scope="scope">
            {{ scope.row.createdUser?scope.row.createdUser.name:'' }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].visible" prop="createTime" label="创建时间" />
        <el-table-column width="170px" label="操作">
          <template slot-scope="scope">
            <el-popconfirm title="您确定要删除吗？" style="margin-right: 5px" @confirm="deleteByIds([scope.row.id])">
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
            </el-popconfirm>
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)" />
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleSubCreate(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <pagination v-show="total>0" :total="total" :page.sync="page.pageNum" :limit.sync="page.pageSize" @pagination="queryAll" />
    </el-card>
    <!--对话框-->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="40%" @open="openDialog">
      <el-row :gutter="15">
        <el-form ref="formData" :model="formData" :rules="rules" size="mini" label-width="100px">
          <el-col :span="24">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入部门名称" maxlength="255" show-word-limit clearable :style="{width: '100%'}" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="formData.sort" placeholder="排序" :min="0" :max="9999" :step="1" :style="{width: '100%'}" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用" prop="frame">
              <el-radio-group v-model="formData.enabled" size="mini">
                <el-radio-button :label="true">是</el-radio-button>
                <el-radio-button :label="false">否</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上级目录" prop="pid">
              <treeselect
                v-model="formData.pid"
                :append-to-body="true"
                z-index="9999"
                :show-count="true"
                search-nested
                :options="depts"
                :normalizer="normalizer"
                placeholder="选择上级类目"
                no-children-text="当前菜单下无子部门"
                no-results-text="查无此部门"
              />
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" size="mini" @click="title==='添加'?create():updateById()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import RightToolbar from '@/components/RightToolbar'
import Pagination from '@/components/Pagination'
import { create, deleteByIds, findAll, findByPid, updateById, tree } from '@/api/dept'
import { Notification } from 'element-ui'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Dept',
  components: { Pagination, RightToolbar, Treeselect },
  data() {
    return {
      dialogVisible: false,
      title: '添加',
      showSearch: true,
      depts: [{ id: 0, name: '顶级部门', children: [] }],
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      },
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
      },
      listQuery: {
        pid: 0,
        name: undefined
      },
      formData: {
        id: undefined,
        pid: 0,
        name: '',
        sort: 9999,
        enabled: true
      },
      selectionChange: null,
      total: 0,
      ids: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        sort: '+sort'
      },
      hasDelObj: true,
      hasEdiObj: true,
      columns: [
        { key: 0, label: `部门名称`, visible: true },
        { key: 1, label: `排序`, visible: true },
        { key: 2, label: `是否启用`, visible: true },
        { key: 3, label: `创建人`, visible: true },
        { key: 4, label: `创建时间`, visible: true }
      ],
      tableData: [],
      loading: false
    }
  },
  created() {
    this.queryAll()
  },
  methods: {
    openDialog() {
      tree().then(res => {
        this.$nextTick(() => { this.depts[0].children = res })
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.queryAll()
    },
    queryAll: function() {
      this.loading = true
      this.tableData = []
      findAll(this.page, this.listQuery).then(res => {
        this.tableData = res.rows
        this.total = res.total
        setTimeout(() => { this.loading = false }, 500)
      }).catch(() => {
        this.loading = false
      })
    },
    updateEnabled(data, row) {
      updateById(data).then(res => {
        Notification.success(res)
      }).catch(err => {
        Notification.error(err)
        row.enabled = !row.enabled
      })
    },
    resetForm() {
      this.listQuery = { pid: 0, name: undefined }
      this.handleFilter()
    },
    handleSubCreate(row) {
      this.formData = {
        id: undefined,
        pid: row.id,
        name: '',
        sort: 9999,
        enabled: row.enabled
      }
      this.title = '添加'
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs['formData'].clearValidate() })
    },
    handleCreate() {
      this.formData = {
        id: undefined,
        pid: 0,
        name: '',
        sort: 9999,
        enabled: true
      }
      this.title = '添加'
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs['formData'].clearValidate() })
    },
    handleUpdate(row) {
      this.formData = Object.assign({}, row) // copy obj
      this.title = '修改'
      this.dialogVisible = true
      this.$nextTick(() => { this.$refs['formData'].clearValidate() })
    },
    handleDelete() {
      if (this.ids.length === 0) {
        Notification.warning('请选择要删除的菜单')
        return
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteByIds(this.ids)
      })
    },
    load(tree, treeNode, resolve) {
      setTimeout(() => {
        findByPid(tree.id).then(res => {
          resolve(res)
        })
      }, 1000)
    },
    handleSelectionChange(val) {
      this.selectionChange = val
      this.ids.length = 0
      const _this = this
      if (val.length > 0) {
        this.hasEdiObj = val.length !== 1
        this.hasDelObj = false
      } else {
        this.hasDelObj = true
        this.hasEdiObj = true
      }
      val.forEach((element) => {
        _this.ids.push(element.id)
      })
    },
    create() {
      this.$refs['formData'].validate((valid) => {
        if (!valid) return
        create(this.formData).then(res => {
          this.dialogVisible = false
          Notification.success(res)
          this.handleFilter()
        })
      })
    },
    updateById() {
      this.$refs['formData'].validate((valid) => {
        if (!valid) return
        updateById(this.formData).then(res => {
          this.dialogVisible = false
          Notification.success(res)
          this.handleFilter()
        })
      })
    },
    deleteByIds(ids) {
      if (ids.length > 0) {
        deleteByIds(ids).then(res => {
          Notification.success(res)
          this.handleFilter()
        })
      }
    }
  }
}
</script>

<style scoped>
.opts {
  padding: 4px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}
.opts .opts-right {
  margin-left: auto;
}
</style>
